package repository

import (
	"apiGateWay/internal/model"
	"gorm.io/gorm"
)

// RouteRepository 路由仓库接口
type RouteRepository interface {
	Create(route *model.Route) error
	GetByID(id uint) (*model.Route, error)
	GetAll() ([]*model.Route, error)
	Update(route *model.Route) error
	Delete(id uint) error
	GetByPath(path string) (*model.Route, error)
}

type routeRepository struct {
	db *gorm.DB
}

// NewRouteRepository 创建路由仓库
func NewRouteRepository(db *gorm.DB) RouteRepository {
	return &routeRepository{db: db}
}

func (r *routeRepository) Create(route *model.Route) error {
	return r.db.Create(route).Error
}

func (r *routeRepository) GetByID(id uint) (*model.Route, error) {
	var route model.Route
	err := r.db.First(&route, id).Error
	if err != nil {
		return nil, err
	}
	return &route, nil
}

func (r *routeRepository) GetAll() ([]*model.Route, error) {
	var routes []*model.Route
	err := r.db.Where("is_enabled = ?", true).Find(&routes).Error
	return routes, err
}

func (r *routeRepository) Update(route *model.Route) error {
	return r.db.Save(route).Error
}

func (r *routeRepository) Delete(id uint) error {
	return r.db.Delete(&model.Route{}, id).Error
}

func (r *routeRepository) GetByPath(path string) (*model.Route, error) {
	var route model.Route
	err := r.db.Where("path = ?", path).First(&route).Error
	if err != nil {
		return nil, err
	}
	return &route, nil
}


